{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import joblib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import KFold\n",
    "from sklearn.model_selection import train_test_split\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 特征组合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 21.4 s, sys: 4.26 s, total: 25.7 s\n",
      "Wall time: 27.1 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# 导入训练数据集\n",
    "data_date = pd.read_csv('../../preprocess_data/train_x_date.csv').drop(columns=['id','loan_hour'])\n",
    "data_raw = joblib.load('../../preprocess_data_new/train_ax_nodup.lz4').head(33465).drop(columns=['loan_dt','id','tag'])\n",
    "data_null = pd.read_csv('../../preprocess_data_new/train_ax_row_null.csv',nrows=33465).drop(columns=['id'])\n",
    "data_tag = pd.read_csv('../../preprocess_data/train_x_33465.csv',usecols=['tag'])\n",
    "week_df = joblib.load('../../preprocess_data_discrete/week_df.lz4').head(33465)\n",
    "\n",
    "# maj_cnt_df = joblib.load('../../preprocess_data_discrete/maj_cnt_df.lz4').head(33465)\n",
    "# cat_df = joblib.load('../../preprocess_data_discrete/cat_df.lz4').head(33465)\n",
    "# discrete_df = joblib.load('../../preprocess_data_discrete/discrete_df.lz4').head(33465)\n",
    "# scale_df = joblib.load('../../preprocess_data_discrete/scale_df.lz4').head(33465)\n",
    "# major_df = joblib.load('../../preprocess_data_discrete/major_df.lz4').head(33465)\n",
    "# day_val_df = joblib.load('../../preprocess_data_discrete/day_val_df.lz4').head(33465)\n",
    "\n",
    "data_label = pd.read_csv('../../preprocess_data/train_y_33465.csv',usecols=['label'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>loan_week_day</th>\n",
       "      <th>week_day_val</th>\n",
       "      <th>week_day_state</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2</td>\n",
       "      <td>0.066868</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3</td>\n",
       "      <td>0.063787</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>6</td>\n",
       "      <td>0.075942</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3</td>\n",
       "      <td>0.063787</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>6</td>\n",
       "      <td>0.075942</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   loan_week_day  week_day_val  week_day_state\n",
       "0              2      0.066868               1\n",
       "1              3      0.063787               0\n",
       "2              6      0.075942               1\n",
       "3              3      0.063787               0\n",
       "4              6      0.075942               1"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "week_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = pd.concat([data_date,data_raw,data_null,data_tag],axis=1,copy=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(33465, 6702)"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = data.fillna(-1).values\n",
    "y = data_label.values.ravel()\n",
    "x.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 数据线上和线下"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 15.7 s, sys: 1.54 s, total: 17.2 s\n",
      "Wall time: 17.2 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# 本地验证\n",
    "# 1.根据有标签数据，生成一个和线上测试集分布相近的本地验证集\n",
    "# tag=0 取600个左右\n",
    "x_train_0, x_test_0, y_train_0, y_test_0 = train_test_split(x[:30465],y[:30465],\n",
    "                                                          random_state=3096,test_size=0.02,stratify=y[:30465])\n",
    "\n",
    "# tag=1 取1500个左右 \n",
    "x_train_1, x_test_1, y_train_1, y_test_1 = train_test_split(x[30465:],y[30465:],\n",
    "                                                            random_state=2018,test_size=0.5,stratify=y[30465:])\n",
    "\n",
    "x_train = np.vstack((x_train_0,x_train_1))\n",
    "x_test = np.vstack((x_test_0,x_test_1))\n",
    "y_train = np.hstack((y_train_0,y_train_1))\n",
    "y_test = np.hstack((y_test_0,y_test_1))\n",
    "# 2. 过采样\n",
    "# from imblearn.over_sampling import BorderlineSMOTE\n",
    "# x_resampled, y_resampled = BorderlineSMOTE().fit_resample(x_train, y_train)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((31355, 6702), (2110, 6702))"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x_train.shape,x_test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((31355,), (2110,))"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_train.shape,y_test.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 本地"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始训练！\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[Parallel(n_jobs=40)]: Using backend ThreadingBackend with 40 concurrent workers.\n",
      "[Parallel(n_jobs=40)]: Done 120 tasks      | elapsed:    8.6s\n",
      "[Parallel(n_jobs=40)]: Done 370 tasks      | elapsed:   23.5s\n",
      "[Parallel(n_jobs=40)]: Done 720 tasks      | elapsed:   44.7s\n",
      "[Parallel(n_jobs=40)]: Done 1000 out of 1000 | elapsed:  1.0min finished\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 38min 32s, sys: 2min 47s, total: 41min 19s\n",
      "Wall time: 2min 50s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "#2.建立模型 \n",
    "model_names = ['rfc','gbc','xgb','lgb']\n",
    "model_name = model_names[0]\n",
    "if model_name == 'rfc':\n",
    "    # RandomForestClassifier\n",
    "    from sklearn.ensemble import RandomForestClassifier\n",
    "    rfc  =RandomForestClassifier(n_estimators=1000,oob_score=True,max_depth=100,\n",
    "                                 n_jobs =40,max_features='sqrt',class_weight='balanced',verbose =1,random_state=2018)\n",
    "elif model_name == 'gbc':\n",
    "    from sklearn.ensemble import GradientBoostingClassifier\n",
    "    gbc = GradientBoostingClassifier(loss='deviance',learning_rate =0.1,n_estimators=300,subsample=0.9,max_depth=3,verbose=1,random_state=2018)\n",
    "elif model_name == 'xgb':\n",
    "    import xgboost as xgb\n",
    "    params={\n",
    "    'booster':'gbtree',\n",
    "    'objective': 'binary:logistic',\n",
    "    'early_stopping_rounds':100,\n",
    "    'scale_pos_weight': float(len(data_label)-np.sum(data_label.values))/float(np.sum(data_label.values)),  # 负例样本除以正例样本\n",
    "    'eval_metric': 'auc',\n",
    "    'gamma':1,\n",
    "    'max_depth':6,\n",
    "    'lambda':1,\n",
    "    'subsample':0.9,\n",
    "    'colsample_bytree':0.9,\n",
    "    'min_child_weight':1, \n",
    "    'eta': 0.04,\n",
    "    'seed':2010,\n",
    "    'nthread':32\n",
    "        }\n",
    "elif model_name == 'lgb':\n",
    "    import lightgbm as lgb\n",
    "    parameters = {\n",
    "        'boost':'gbdt',\n",
    "        'num_leaves':135, \n",
    "        'scale_pos_weight':float(len(y_train)-np.sum(y_train.ravel()))/float(np.sum(y_train.ravel())),\n",
    "        'max_depth':-1,\n",
    "        'learning_rate':.05,\n",
    "        'max_bin':200,\n",
    "        'min_data_in_leaf' : 60,\n",
    "        'objective':'binary',\n",
    "        'metric':'auc',\n",
    "        'verbose':1,\n",
    "        'num_threads':36\n",
    "    }\n",
    "       \n",
    "else:\n",
    "    pass\n",
    "\n",
    "#3.训练模型\n",
    "print('开始训练！')\n",
    "import joblib\n",
    "if model_name == 'rfc':\n",
    "    rfc.fit(x_train,y_train)\n",
    "#     joblib.dump(rfc,'./model/rfc_model')\n",
    "elif model_name == 'gbc':\n",
    "    gbc.fit(x_train,y_train)\n",
    "#     joblib.dump(gbc,'./model/rgbc_model')\n",
    "elif model_name =='xgb':\n",
    "    dtrain = xgb.DMatrix(x_train,y_train)\n",
    "    dvalid = xgb.DMatrix(x_test,y_test)\n",
    "    dtest = xgb.DMatrix(x_test)\n",
    "    watchlist  = [(dvalid,'valid')]\n",
    "    xgb_model = xgb.train(params,dtrain,num_boost_round=300,evals=watchlist)\n",
    "#     xgb_model.save_model('./model/xgb_model')\n",
    "elif model_name == 'lgb':\n",
    "    lgb_train = lgb.Dataset(x_train, y_train.ravel())\n",
    "    lgb_model = lgb.train(parameters,lgb_train,num_boost_round=300)\n",
    "#     lgb_model.save_model('./model/lgb_model')\n",
    "else:\n",
    "    pass\n",
    "# lg.fit(x_train,y_train.ravel())\n",
    "# lsvm.fit(x_train,y_train)\n",
    "# history = model.fit(x_train,y_train,epochs=2,batch_size=1024,class_weight = 'auto',validation_data=(x_test,y_test))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始预测！\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[Parallel(n_jobs=40)]: Using backend ThreadingBackend with 40 concurrent workers.\n",
      "[Parallel(n_jobs=40)]: Done 120 tasks      | elapsed:    0.1s\n",
      "[Parallel(n_jobs=40)]: Done 370 tasks      | elapsed:    0.2s\n",
      "[Parallel(n_jobs=40)]: Done 720 tasks      | elapsed:    0.4s\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AUC: 0.7800153853269748\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[Parallel(n_jobs=40)]: Done 1000 out of 1000 | elapsed:    0.5s finished\n"
     ]
    }
   ],
   "source": [
    "#4.预测结果\n",
    "print('开始预测！')\n",
    "if model_name=='rfc':\n",
    "    y_pre = rfc.predict_proba(x_test)[:,1]\n",
    "elif model_name=='gbc':\n",
    "    y_pre = gbc.predict_proba(x_test)[:,1]\n",
    "elif model_name=='xgb':\n",
    "    dtest = xgb.DMatrix(x_test)\n",
    "    y_pre = xgb_model.predict(dtest).ravel()\n",
    "elif model_name=='lgb':\n",
    "    y_pre = lgb_model.predict(x_test)\n",
    "else:\n",
    "    pass\n",
    "\n",
    "# y_pre = lsvm.decision_function(X_test)\n",
    "# y_pre = lg.predict(X_test)\n",
    "from sklearn import metrics\n",
    "auc = metrics.roc_auc_score(y_test, y_pre)\n",
    "print('AUC:',auc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9382554616488599"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rfc.oob_score_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 未作stratify\n",
    "nodup + null + tag +(fillna(-1))AUC: 0.82785  \n",
    "nodup + null + tag +(fillna(-1)) + maj_cnt AUC:    \n",
    "nodup + null + tag +(fillna(-1)) + major_df + maj_cnt_df  AUC: 0.832029(200)\n",
    "nodup + null + tag +(fillna(-1)) + major_df AUC:0.829731  \n",
    "nodup + null + tag +(fillna(-1)) + major_df + maj_cnt_df + discrete_df:0.8301\n",
    "data_raw被替换 AUC：0.821537  \n",
    "nodup + null + tag +(fillna(-1)) + major_df + maj_cnt_df + week_df AUC: 0.826666  \n",
    "nodup + null + tag +(fillna(-1))  + maj_cnt_df + week_df AUC:0.828063  \n",
    "nodup + null + tag +(fillna(-1))  + maj_cnt_df + maj_cnt_df + day_val_df AUC: 0.828095"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## stratify\n",
    "#### xgboost  \n",
    "nodup + null + tag +(fillna(-1)) AUC:0.814429(200)  \n",
    "nodup + null + tag +(fillna(-1)) + week_df AUC:0.816316(232)  \n",
    "nodup + null + tag +(fillna(-1)) + week_df + maj_cnt_df AUC:0.815836(168)\n",
    "#### rfc  \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
